package org.ehe.business.step.service;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.ehe.business.step.domain.GeometryAnalysis;
import org.ehe.business.step.domain.ManufacturingEstimate;
import org.ehe.business.step.domain.STEPAnalysisResult;
import org.ehe.business.step.pdf.PDFGenerator;
import org.ehe.business.step.pdf.Render3DModelPreview;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 增强版STEP文件分析服务
 */
@Service
@Slf4j
public class EnhancedSTEPAnalyzerService {

    @Resource
    private PDFGenerator pdfGenerator;
    @Resource
    private Render3DModelPreview render3DModelPreview;

    /**
     * 增强版STEP文件分析，包含更详细的几何分析
     */
    public STEPAnalysisResult enhancedAnalysis(File stepFile,String fileName) throws IOException {
        long startTime = System.currentTimeMillis();
        STEPAnalysisResult result = new STEPAnalysisResult();
        result.setRequestId("EIAHE"+System.currentTimeMillis());
        result.setFileName(fileName);
        log.info("开始增强分析STEP文件: {}", stepFile.getName());

        try {
            String content = readFileContent(stepFile);

            // 基础信息解析
            parseBasicInfo(content, result);
            result.setFileSize(stepFile.length());

            // 3D模型预览生成（优先执行，确保有视觉反馈）
            log.info("开始生成3D模型预览...");
            String modelPreviewPath = render3DModelPreview.modelPreview(stepFile);
            result.setModelPreviewPath(modelPreviewPath);

            if (modelPreviewPath != null) {
                log.info("3D模型预览生成成功: {}", modelPreviewPath);
            } else {
                log.warn("3D模型预览生成失败，将在PDF中显示占位信息");
            }

            // 详细几何分析
            log.info("开始详细几何分析...");
            GeometryAnalysis geometryAnalysis = performAdvancedGeometryAnalysis(content);
            result.setGeometryAnalysis(geometryAnalysis);

            // 高级制造估算
            log.info("开始制造估算分析...");
            ManufacturingEstimate estimate = performAdvancedEstimation(result, geometryAnalysis);
            result.setManufacturingEstimate(estimate);

            // 质量评估
            log.info("开始质量评估...");
            performComprehensiveQualityAssessment(result, content, geometryAnalysis);

            long processingTime = System.currentTimeMillis() - startTime;
            result.setProcessingTimeMs(processingTime);

            log.info("STEP文件增强分析完成，耗时: {}ms", processingTime);

            // 生成PDF报告
            log.info("生成PDF分析报告...");
            String pdfPath = pdfGenerator.generatePDFReport(result, stepFile.getName());
            result.setPdfReportPath(pdfPath);
        } catch (Exception e) {
            log.error("STEP文件分析过程中出现错误", e);
            throw e;
        }

        return result;
    }

    /**
     * 执行高级几何分析
     */
    private GeometryAnalysis performAdvancedGeometryAnalysis(String content) {
        GeometryAnalysis analysis = new GeometryAnalysis();
        log.debug("开始高级几何分析");

        // 1. 计算精确边界框
        calculatePreciseBoundingBox(content, analysis);

        // 2. 深度表面特征分析
        analyzeAdvancedSurfaceFeatures(content, analysis);

        // 3. 智能加工特征识别
        detectIntelligentMachiningFeatures(content, analysis);

        // 4. 体积和表面积估算
        estimateVolumeAndSurfaceArea(content, analysis);

        // 5. 几何复杂度评估
        assessGeometricComplexity(analysis);

        // 6. 公差和精度分析
        analyzeToleranceRequirements(content, analysis);

        log.debug("几何分析完成 - 复杂度评分: {}", analysis.getSurfaceComplexityScore());
        return analysis;
    }

    private void calculatePreciseBoundingBox(String content, GeometryAnalysis analysis) {
        Pattern pointPattern = Pattern.compile(
            "#\\d+\\s*=\\s*CARTESIAN_POINT\\s*\\(\\s*'[^']*'\\s*,\\s*\\(([^)]+)\\)\\s*\\)",
            Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = pointPattern.matcher(content);

        List<double[]> points = new ArrayList<>();
        double minX = Double.MAX_VALUE, maxX = Double.MIN_VALUE;
        double minY = Double.MAX_VALUE, maxY = Double.MIN_VALUE;
        double minZ = Double.MAX_VALUE, maxZ = Double.MIN_VALUE;

        int pointCount = 0;
        while (matcher.find()) {
            String coordinates = matcher.group(1);
            String[] coords = coordinates.split(",");

            if (coords.length >= 3) {
                try {
                    double x = Double.parseDouble(coords[0].trim());
                    double y = Double.parseDouble(coords[1].trim());
                    double z = Double.parseDouble(coords[2].trim());

                    points.add(new double[]{x, y, z});

                    minX = Math.min(minX, x);
                    maxX = Math.max(maxX, x);
                    minY = Math.min(minY, y);
                    maxY = Math.max(maxY, y);
                    minZ = Math.min(minZ, z);
                    maxZ = Math.max(maxZ, z);

                    pointCount++;
                } catch (NumberFormatException e) {
                    // 忽略无效坐标
                }
            }
        }

        if (minX != Double.MAX_VALUE) {
            double length = maxX - minX;
            double width = maxY - minY;
            double height = maxZ - minZ;

            analysis.setBoundingBox(new double[]{length, width, height});
            analysis.setDimensions(String.format("%.2f × %.2f × %.2f mm", length, width, height));

            log.debug("边界框计算完成: {} 个点, 尺寸: {}", pointCount, analysis.getDimensions());
        } else {
            analysis.setDimensions("无法确定尺寸");
            log.warn("未找到有效的坐标点");
        }
    }

    private void analyzeAdvancedSurfaceFeatures(String content, GeometryAnalysis analysis) {
        Map<String, Integer> surfaceTypes = new HashMap<>();

        // 扩展的表面类型检测
        Map<String, String> surfacePatterns = Map.of(
            "PLANE", "平面",
            "CYLINDRICAL_SURFACE", "圆柱面",
            "SPHERICAL_SURFACE", "球面",
            "CONICAL_SURFACE", "圆锥面",
            "TOROIDAL_SURFACE", "环面",
            "B_SPLINE_SURFACE", "B样条曲面",
            "BEZIER_SURFACE", "贝塞尔曲面",
            "SURFACE_OF_REVOLUTION", "回转面",
            "SWEPT_SURFACE", "扫掠面",
            "OFFSET_SURFACE", "偏移面"
        );

        for (Map.Entry<String, String> entry : surfacePatterns.entrySet()) {
            String surfaceType = entry.getKey();
            Pattern pattern = Pattern.compile("#\\d+\\s*=\\s*" + surfaceType, Pattern.CASE_INSENSITIVE);
            int count = countMatches(pattern, content);
            if (count > 0) {
                surfaceTypes.put(entry.getValue(), count);
                log.debug("检测到表面类型: {} - {} 个", entry.getValue(), count);
            }
        }

        analysis.setSurfaceTypes(surfaceTypes);

        // 计算表面复杂度评分
        int complexityScore = surfaceTypes.entrySet().stream()
            .mapToInt(entry -> {
                int weight = getSurfaceComplexityWeight(entry.getKey());
                return entry.getValue() * weight;
            }).sum();

        analysis.setSurfaceComplexityScore(complexityScore);
        log.debug("表面复杂度评分: {}", complexityScore);
    }

    private void detectIntelligentMachiningFeatures(String content, GeometryAnalysis analysis) {
        List<String> features = new ArrayList<>();
        Map<String, String> featureDetails = new HashMap<>();

        // 1. 孔特征检测（更精确）
        int holeCount = detectHoleFeatures(content);
        if (holeCount > 0) {
            features.add("孔加工");
            featureDetails.put("孔数量", String.valueOf(holeCount));

            // 检测孔的类型
            List<String> holeTypes = detectHoleTypes(content);
            if (!holeTypes.isEmpty()) {
                featureDetails.put("孔类型", String.join(", ", holeTypes));
            }
        }

        // 2. 槽和腔体特征
        if (detectSlotAndPocketFeatures(content)) {
            features.add("槽/腔体加工");
            featureDetails.put("槽腔复杂度", assessSlotComplexity(content));
        }

        // 3. 螺纹特征
        if (detectThreadFeatures(content)) {
            features.add("螺纹加工");
            featureDetails.put("螺纹规格", detectThreadSpecs(content));
        }

        // 4. 倒角和圆角
        Map<String, Integer> filletChamferCount = detectFilletChamferFeatures(content);
        if (!filletChamferCount.isEmpty()) {
            features.add("倒角圆角");
            filletChamferCount.forEach((k, v) -> featureDetails.put(k, v.toString()));
        }

        // 5. 键槽特征
        if (detectKeywayFeatures(content)) {
            features.add("键槽加工");
        }

        // 6. 锥度特征
        if (detectTaperFeatures(content)) {
            features.add("锥度加工");
        }

        analysis.setMachiningFeatures(features);
        analysis.setFeatureDetails(featureDetails);

        log.debug("检测到加工特征: {}", features);
    }

    private void estimateVolumeAndSurfaceArea(String content, GeometryAnalysis analysis) {
        // 基于边界框的粗略体积估算
        double[] bbox = analysis.getBoundingBox();
        if (bbox != null && bbox.length == 3) {
            double boundingVolume = bbox[0] * bbox[1] * bbox[2];

            // 根据几何复杂度和实体类型调整体积估算
            double fillFactor = calculateIntelligentFillFactor(content, analysis);
            double estimatedVolume = boundingVolume * fillFactor;

            analysis.setEstimatedVolume(estimatedVolume);
            analysis.setVolumeUnit("立方毫米");

            // 表面积估算（基于表面数量和类型）
            double surfaceArea = estimateSurfaceArea(content, bbox, analysis.getSurfaceTypes());
            analysis.setSurfaceArea(BigDecimal.valueOf(surfaceArea));

            log.debug("体积估算: {:.2f} 立方毫米, 表面积: {:.2f} 平方毫米", estimatedVolume, surfaceArea);
        }
    }

    private void assessGeometricComplexity(GeometryAnalysis analysis) {
        int complexityScore = analysis.getSurfaceComplexityScore();

        // 基于特征数量调整复杂度
        if (analysis.getMachiningFeatures() != null) {
            complexityScore += analysis.getMachiningFeatures().size() * 15;
        }

        // 基于表面数量调整
        if (analysis.getSurfaceTypes() != null) {
            int totalSurfaces = analysis.getSurfaceTypes().values().stream().mapToInt(Integer::intValue).sum();
            complexityScore += totalSurfaces * 2;
        }

        analysis.setSurfaceComplexityScore(complexityScore);
    }

    private void analyzeToleranceRequirements(String content, GeometryAnalysis analysis) {
        StringBuilder toleranceInfo = new StringBuilder();

        // 检测尺寸公差标注
        if (content.contains("DIMENSIONAL_TOLERANCE") || content.contains("GEOMETRIC_TOLERANCE")) {
            toleranceInfo.append("发现公差标注; ");
        }

        // 检测形状公差
        if (content.contains("FLATNESS") || content.contains("STRAIGHTNESS") ||
            content.contains("ROUNDNESS") || content.contains("CYLINDRICITY")) {
            toleranceInfo.append("包含形状公差; ");
        }

        // 检测位置公差
        if (content.contains("POSITION") || content.contains("CONCENTRICITY") ||
            content.contains("PERPENDICULARITY") || content.contains("PARALLELISM")) {
            toleranceInfo.append("包含位置公差; ");
        }

        analysis.setToleranceInfo(toleranceInfo.length() > 0 ? toleranceInfo.toString() : "未发现公差要求");
    }

    private ManufacturingEstimate performAdvancedEstimation(STEPAnalysisResult result, GeometryAnalysis geometryAnalysis) {
        ManufacturingEstimate estimate = new ManufacturingEstimate();

        log.debug("开始高级制造估算");

        // 智能工艺规划
        List<String> recommendedProcesses = planIntelligentManufacturingProcesses(geometryAnalysis);
        estimate.setRecommendedProcesses(recommendedProcesses);

        // 精确时间估算
        calculatePreciseTimeEstimate(geometryAnalysis, estimate);

        // 材料利用率分析
        calculateAdvancedMaterialUtilization(geometryAnalysis, estimate);

        // 加工难度评估
        assessComprehensiveMachiningDifficulty(geometryAnalysis, estimate);

        // 设备需求分析
        analyzeEquipmentRequirements(geometryAnalysis, estimate);

        // 成本明细计算
        calculateDetailedCostBreakdown(estimate, geometryAnalysis);

        // 质量和精度要求
        assessQualityRequirements(geometryAnalysis, estimate);



        log.debug("制造估算完成 - 预估成本: ¥{:.2f}", estimate.getEstimatedCost());
        return estimate;
    }

    private List<String> planIntelligentManufacturingProcesses(GeometryAnalysis analysis) {
        List<String> processes = new LinkedList<>();

        // 基础工艺规划
        if (analysis.getSurfaceComplexityScore() > 200) {
            processes.add("粗加工");
            processes.add("半精加工");
            processes.add("精加工");
        } else if (analysis.getSurfaceComplexityScore() > 50) {
            processes.add("粗加工");
            processes.add("精加工");
        } else {
            processes.add("直接精加工");
        }

        // 根据加工特征添加专门工艺
        if (analysis.getMachiningFeatures() != null) {
            for (String feature : analysis.getMachiningFeatures()) {
                switch (feature) {
                    case "孔加工":
                        if (!processes.contains("钻孔")) {
                            processes.add("钻孔");
                            // 根据孔的数量和类型决定是否需要扩孔、铰孔
                            String holeCount = analysis.getFeatureDetails().get("孔数量");
                            if (holeCount != null && Integer.parseInt(holeCount) > 5) {
                                processes.add("扩孔");
                            }
                        }
                        break;
                    case "槽/腔体加工":
                        if (!processes.contains("铣削")) {
                            processes.add("铣削");
                        }
                        break;
                    case "螺纹加工":
                        processes.add("攻丝/套丝");
                        break;
                    case "倒角圆角":
                        processes.add("倒角/圆角加工");
                        break;
                    case "键槽加工":
                        processes.add("键槽铣削");
                        break;
                }
            }
        }

        // 后处理工艺
        if (analysis.getSurfaceComplexityScore() > 100) {
            processes.add("去毛刺");
            processes.add("表面处理");
        }

        return processes;
    }

    private void calculatePreciseTimeEstimate(GeometryAnalysis analysis, ManufacturingEstimate estimate) {
        double totalTime = 0;
        Map<String, Double> processTime = new HashMap<>();

        // 基于体积的基础加工时间（改进算法）
        double volume = analysis.getEstimatedVolume();
        double materialRemovalRate = 1000; // mm³/min
        double baseTime = volume / materialRemovalRate; // 分钟

        // 复杂度调整系数
        double complexityMultiplier = 1 + (analysis.getSurfaceComplexityScore() / 500.0);
        baseTime *= complexityMultiplier;

        processTime.put("主要加工", baseTime);
        totalTime += baseTime;

        // 特征加工时间（更精确）
        if (analysis.getMachiningFeatures() != null) {
            for (String feature : analysis.getMachiningFeatures()) {
                double featureTime = calculatePreciseFeatureTime(feature, analysis);
                processTime.put(feature, featureTime);
                totalTime += featureTime;
            }
        }

        // 辅助时间（装夹、测量等）
        double auxiliaryTime = totalTime * 0.3; // 30%的辅助时间
        processTime.put("辅助时间", auxiliaryTime);
        totalTime += auxiliaryTime;

        estimate.setMachiningHours((int) Math.ceil(totalTime / 60)); // 转换为小时
        estimate.setEstimatedDays((int) Math.ceil(estimate.getMachiningHours()/24)+ 1);
        estimate.setProcessTimeBredown(processTime);
    }

    private void calculateAdvancedMaterialUtilization(GeometryAnalysis analysis, ManufacturingEstimate estimate) {
        double[] bbox = analysis.getBoundingBox();
        if (bbox != null) {
            // 考虑实际加工余量
            double margin = 5.0; // 5mm加工余量
            double rawLength = bbox[0] + 2 * margin;
            double rawWidth = bbox[1] + 2 * margin;
            double rawHeight = bbox[2] + 2 * margin;

            double rawMaterialVolume = rawLength * rawWidth * rawHeight;
            double partVolume = analysis.getEstimatedVolume();

            // 考虑切削液、夹具等因素
            double practicalUtilization = (partVolume / rawMaterialVolume) * 0.85; // 85%实际利用率

            estimate.setMaterialUtilization(practicalUtilization * 100);
            estimate.setRawMaterialVolume(rawMaterialVolume);

            // 估算材料重量（假设铝合金，密度2.7g/cm³）
            double materialWeight = rawMaterialVolume / 1000 * 2.7; // 转换为克
            estimate.setEstimatedMaterialVolume(materialWeight / 1000); // 转换为千克
        }
    }

    private void assessComprehensiveMachiningDifficulty(GeometryAnalysis analysis, ManufacturingEstimate estimate) {
        int difficultyScore = 0;

        // 基于表面复杂度
        difficultyScore += Math.min(analysis.getSurfaceComplexityScore() / 10, 50);

        // 基于加工特征复杂度
        if (analysis.getMachiningFeatures() != null) {
            for (String feature : analysis.getMachiningFeatures()) {
                difficultyScore += getFeatureDifficultyScore(feature);
            }
        }

        // 基于尺寸
        double[] bbox = analysis.getBoundingBox();
        if (bbox != null) {
            double maxDimension = Math.max(Math.max(bbox[0], bbox[1]), bbox[2]);
            double minDimension = Math.min(Math.min(bbox[0], bbox[1]), bbox[2]);

            if (maxDimension > 500) difficultyScore += 20; // 大尺寸
            if (minDimension < 5) difficultyScore += 30;   // 小特征精密加工

            // 长宽比检查
            double aspectRatio = maxDimension / minDimension;
            if (aspectRatio > 10) difficultyScore += 25; // 细长比大
        }

        // 公差要求
        String toleranceInfo = analysis.getToleranceInfo();
        if (toleranceInfo != null && !toleranceInfo.contains("未发现")) {
            difficultyScore += 30;
        }

        String difficulty;
        String riskLevel;
        if (difficultyScore < 30) {
            difficulty = "简单";
            riskLevel = "低";
        } else if (difficultyScore < 80) {
            difficulty = "中等";
            riskLevel = "中";
        } else {
            difficulty = "困难";
            riskLevel = "高";
        }

        estimate.setDifficultyLevel(difficulty);
        estimate.setDifficultyScore(difficultyScore);
        estimate.setRiskLevel(riskLevel);

        // 精度等级评估
        estimate.setPrecisionLevel(assessPrecisionLevel(analysis));
    }

    private void analyzeEquipmentRequirements(GeometryAnalysis analysis, ManufacturingEstimate estimate) {
        List<String> requiredEquipment = new ArrayList<>();

        // 基于尺寸确定机床规格
        double[] bbox = analysis.getBoundingBox();
        if (bbox != null) {
            double maxDim = Math.max(Math.max(bbox[0], bbox[1]), bbox[2]);
            if (maxDim < 100) {
                estimate.setMinMachineSize("小型机床 (100×100mm)");
                requiredEquipment.add("小型数控铣床");
            } else if (maxDim < 500) {
                estimate.setMinMachineSize("中型机床 (500×500mm)");
                requiredEquipment.add("中型数控铣床");
            } else {
                estimate.setMinMachineSize("大型机床 (1000×1000mm+)");
                requiredEquipment.add("大型数控铣床");
            }
        }

        // 基于加工特征确定设备
        if (analysis.getMachiningFeatures() != null) {
            for (String feature : analysis.getMachiningFeatures()) {
                switch (feature) {
                    case "孔加工":
                        requiredEquipment.add("钻床/加工中心");
                        break;
                    case "螺纹加工":
                        requiredEquipment.add("攻丝设备");
                        break;
                    case "槽/腔体加工":
                        requiredEquipment.add("铣床/加工中心");
                        break;
                }
            }
        }

        estimate.setRequiredEquipment(requiredEquipment);
    }

    private void calculateDetailedCostBreakdown(ManufacturingEstimate estimate, GeometryAnalysis analysis) {
        Map<String, Double> costBreakdown = new HashMap<>();

        // 1. 材料成本
        double materialVolume = estimate.getRawMaterialVolume(); // 立方毫米
        double materialDensity = 2.7; // 铝合金密度 g/cm³
        double materialWeight = materialVolume / 1000 * materialDensity / 1000; // 转换为kg
        double materialPrice = 25.0; // 25元/kg
        double materialCost = materialWeight * materialPrice;
        costBreakdown.put("原材料成本", materialCost);

        // 2. 加工成本
        int machiningHours = estimate.getMachiningHours();
        double hourlyRate = 120; // 120元/小时（包含人工和机床）
        double machiningCost = machiningHours * hourlyRate;
        costBreakdown.put("加工费用", machiningCost);

        // 3. 刀具成本
        double toolCost = machiningHours * 15; // 15元/小时刀具损耗
        costBreakdown.put("刀具成本", toolCost);

        // 4. 设备折旧
        double equipmentCost = machiningHours * 25; // 25元/小时设备折旧
        costBreakdown.put("设备折旧", equipmentCost);

        // 5. 质量检测费用
        double inspectionCost = 50; // 基础检测费用
        if ("高".equals(estimate.getRiskLevel())) {
            inspectionCost *= 2; // 高风险项目检测费用翻倍
        }
        costBreakdown.put("质量检测", inspectionCost);

        // 6. 管理费用
        double directCost = materialCost + machiningCost + toolCost + equipmentCost;
        double managementCost = directCost * 0.20; // 20%管理费用
        costBreakdown.put("管理费用", managementCost);

        // 7. 利润
        double totalCost = directCost + inspectionCost + managementCost;
        double profit = totalCost * 0.15; // 15%利润率
        costBreakdown.put("利润", profit);

        double finalCost = totalCost + profit;

        estimate.setCostBreakdown(costBreakdown);
        estimate.setEstimatedCost(finalCost);
    }

    private void assessQualityRequirements(GeometryAnalysis analysis, ManufacturingEstimate estimate) {
        List<String> specialRequirements = new ArrayList<>();

        // 基于公差要求
        String toleranceInfo = analysis.getToleranceInfo();
        if (toleranceInfo != null && !toleranceInfo.contains("未发现")) {
            specialRequirements.add("严格公差控制");
            specialRequirements.add("三坐标测量");
        }

        // 基于表面复杂度
        if (analysis.getSurfaceComplexityScore() > 300) {
            specialRequirements.add("表面粗糙度检测");
            specialRequirements.add("轮廓度测量");
        }

        // 基于材料和结构
        if (analysis.getBoundingBox() != null) {
            double[] bbox = analysis.getBoundingBox();
            double wallThickness = Math.min(Math.min(bbox[0], bbox[1]), bbox[2]);
            if (wallThickness < 2) {
                specialRequirements.add("薄壁件加工工艺");
                specialRequirements.add("变形控制");
            }
        }

        estimate.setSpecialRequirements(specialRequirements);
    }

    private void performComprehensiveQualityAssessment(STEPAnalysisResult result, String content, GeometryAnalysis analysis) {
        List<String> qualityIssues = new ArrayList<>();
        List<String> recommendations = new ArrayList<>();
        int qualityScore = 100; // 基础分数

        log.debug("开始全面质量评估");

        // 1. 文件完整性检查
        if (!content.contains("END-ISO-10303")) {
            qualityIssues.add("STEP文件可能不完整 - 缺少结束标记");
            qualityScore -= 20;
            recommendations.add("请重新导出完整的STEP文件");
        }

        // 2. 单位系统检查
        if (result.getUnit() == null || result.getUnit().isEmpty()) {
            qualityIssues.add("未明确定义单位系统");
            qualityScore -= 10;
            recommendations.add("在CAD软件中明确设置单位系统");
        }

        // 3. 几何连续性检查
        if (analysis.getSurfaceComplexityScore() > 500) {
            qualityIssues.add("几何结构过于复杂，可能存在连续性问题");
            qualityScore -= 15;
            recommendations.add("考虑简化几何结构或分段加工");
        }

        // 4. 加工可行性检查
        double[] bbox = analysis.getBoundingBox();
        if (bbox != null) {
            double aspectRatio = Math.max(Math.max(bbox[0], bbox[1]), bbox[2]) /
                Math.min(Math.min(bbox[0], bbox[1]), bbox[2]);
            if (aspectRatio > 20) {
                qualityIssues.add("零件长宽比过大，可能导致加工变形");
                qualityScore -= 10;
                recommendations.add("考虑使用专用夹具和分段加工");
            }
        }

        // 5. 材料信息完整性
        if (result.getMaterials() == null || result.getMaterials().isEmpty() ||
            result.getMaterials().contains("未指定材料")) {
            qualityIssues.add("缺少材料信息");
            qualityScore -= 5;
            recommendations.add("在CAD模型中指定材料属性");
        }

        // 6. 加工特征合理性检查
        if (analysis.getMachiningFeatures() != null) {
            for (String feature : analysis.getMachiningFeatures()) {
                if ("孔加工".equals(feature)) {
                    String holeCount = analysis.getFeatureDetails().get("孔数量");
                    if (holeCount != null && Integer.parseInt(holeCount) > 20) {
                        qualityIssues.add("孔数量较多，需要考虑加工效率");
                        recommendations.add("评估是否可以合并或优化孔的分布");
                    }
                }
            }
        }

        // 7. 设计优化建议
        if (qualityScore > 85) {
            recommendations.add("模型质量良好，可直接进行加工准备");
        } else if (qualityScore > 70) {
            recommendations.add("模型基本合格，建议根据问题列表进行优化");
        } else {
            recommendations.add("模型存在较多问题，强烈建议重新设计或大幅优化");
        }

        result.setQualityIssues(qualityIssues);
        result.setRecommendations(recommendations);
        result.setQualityScore(Math.max(0, qualityScore));

        log.debug("质量评估完成 - 评分: {}/100", result.getQualityScore());
    }

    // ========== 辅助方法 ==========

    private double calculateIntelligentFillFactor(String content, GeometryAnalysis analysis) {
        double fillFactor = 0.6; // 基础填充系数

        // 根据实体类型调整
        if (content.contains("MANIFOLD_SOLID_BREP")) {
            fillFactor = 0.75; // 实体模型
        } else if (content.contains("SHELL_BASED_SURFACE_MODEL")) {
            fillFactor = 0.25; // 表面模型
        }

        // 根据加工特征调整
        if (analysis.getMachiningFeatures() != null) {
            int featureCount = analysis.getMachiningFeatures().size();
            if (featureCount > 5) {
                fillFactor *= 0.8; // 特征多的零件通常更空
            }
        }

        return Math.max(0.1, Math.min(0.9, fillFactor));
    }

    private double estimateSurfaceArea(String content, double[] bbox, Map<String, Integer> surfaceTypes) {
        if (bbox == null) return 0;

        // 基础表面积（边界框）
        double baseSurfaceArea = 2 * (bbox[0] * bbox[1] + bbox[1] * bbox[2] + bbox[0] * bbox[2]);

        // 根据表面类型调整
        double complexitMultiplier = 1.0;
        if (surfaceTypes != null) {
            int totalSurfaces = surfaceTypes.values().stream().mapToInt(Integer::intValue).sum();
            complexitMultiplier = 1 + Math.log(totalSurfaces) / 10;
        }

        return baseSurfaceArea * complexitMultiplier;
    }

    private int detectHoleFeatures(String content) {
        // 更精确的孔检测
        Pattern cylindricalPattern = Pattern.compile(
            "#\\d+\\s*=\\s*CYLINDRICAL_SURFACE.*?AXIS2_PLACEMENT",
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL
        );
        return countMatches(cylindricalPattern, content);
    }

    private List<String> detectHoleTypes(String content) {
        List<String> holeTypes = new ArrayList<>();

        if (content.toLowerCase().contains("counterbore")) {
            holeTypes.add("沉头孔");
        }
        if (content.toLowerCase().contains("countersink")) {
            holeTypes.add("埋头孔");
        }
        if (content.toLowerCase().contains("thread") || content.toLowerCase().contains("螺纹")) {
            holeTypes.add("螺纹孔");
        }
        if (holeTypes.isEmpty()) {
            holeTypes.add("通孔");
        }

        return holeTypes;
    }

    private boolean detectSlotAndPocketFeatures(String content) {
        return content.contains("RECTANGULAR_COMPOSITE_CURVE") ||
            content.toLowerCase().contains("slot") ||
            content.toLowerCase().contains("pocket") ||
            (content.contains("PLANE") && content.contains("CYLINDRICAL_SURFACE"));
    }

    private String assessSlotComplexity(String content) {
        int rectangularCurves = countMatches(
            Pattern.compile("RECTANGULAR_COMPOSITE_CURVE", Pattern.CASE_INSENSITIVE), content);

        if (rectangularCurves > 10) return "复杂";
        else if (rectangularCurves > 3) return "中等";
        else return "简单";
    }

    private boolean detectThreadFeatures(String content) {
        return content.toLowerCase().contains("thread") ||
            content.toLowerCase().contains("螺纹") ||
            content.contains("HELICAL_CURVE") ||
            content.toLowerCase().contains("screw");
    }

    private String detectThreadSpecs(String content) {
        // 简化的螺纹规格检测
        if (content.toLowerCase().contains("m6")) return "M6螺纹";
        if (content.toLowerCase().contains("m8")) return "M8螺纹";
        if (content.toLowerCase().contains("m10")) return "M10螺纹";
        return "标准螺纹";
    }

    private Map<String, Integer> detectFilletChamferFeatures(String content) {
        Map<String, Integer> features = new HashMap<>();

        int chamferCount = countMatches(
            Pattern.compile("chamfer|倒角", Pattern.CASE_INSENSITIVE), content);
        if (chamferCount > 0) {
            features.put("倒角数量", chamferCount);
        }

        int filletCount = countMatches(
            Pattern.compile("fillet|圆角", Pattern.CASE_INSENSITIVE), content);
        if (filletCount > 0) {
            features.put("圆角数量", filletCount);
        }

        return features;
    }

    private boolean detectKeywayFeatures(String content) {
        return content.toLowerCase().contains("keyway") ||
            content.toLowerCase().contains("键槽");
    }

    private boolean detectTaperFeatures(String content) {
        return content.contains("CONICAL_SURFACE") ||
            content.toLowerCase().contains("taper") ||
            content.toLowerCase().contains("锥");
    }

    private double calculatePreciseFeatureTime(String feature, GeometryAnalysis analysis) {
        switch (feature) {
            case "孔加工":
                String holeCount = analysis.getFeatureDetails().get("孔数量");
                int holes = holeCount != null ? Integer.parseInt(holeCount) : 1;
                return holes * 3.0; // 3分钟/孔
            case "槽/腔体加工":
                return 15.0; // 15分钟基础时间
            case "螺纹加工":
                return 5.0; // 5分钟/螺纹
            case "倒角圆角":
                return 8.0; // 8分钟
            case "键槽加工":
                return 20.0; // 20分钟
            default:
                return 5.0;
        }
    }

    private int getFeatureDifficultyScore(String feature) {
        switch (feature) {
            case "孔加工": return 5;
            case "槽/腔体加工": return 15;
            case "螺纹加工": return 10;
            case "倒角圆角": return 3;
            case "键槽加工": return 20;
            case "锥度加工": return 25;
            default: return 5;
        }
    }

    private String assessPrecisionLevel(GeometryAnalysis analysis) {
        String toleranceInfo = analysis.getToleranceInfo();
        if (toleranceInfo != null && !toleranceInfo.contains("未发现")) {
            if (toleranceInfo.contains("位置公差")) return "高精度";
            if (toleranceInfo.contains("形状公差")) return "中高精度";
            return "中精度";
        }
        return "标准精度";
    }

    // 现有的辅助方法保持不变
    private String readFileContent(File file) throws IOException {
        Charset[] charsets = {
            StandardCharsets.UTF_8,
            StandardCharsets.ISO_8859_1,
            Charset.forName("GBK"),
            Charset.forName("GB2312")
        };

        for (Charset charset : charsets) {
            try {
                return Files.readString(file.toPath(), charset);
            } catch (MalformedInputException e) {
                log.debug("尝试使用{}编码读取文件失败，将尝试其他编码", charset.name());
                continue;
            }
        }

        byte[] contentBytes = Files.readAllBytes(file.toPath());
        return new String(contentBytes, StandardCharsets.UTF_8);
    }

    private int countMatches(Pattern pattern, String content) {
        Matcher matcher = pattern.matcher(content);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }

    private int getSurfaceComplexityWeight(String surfaceType) {
        switch (surfaceType) {
            case "平面": return 1;
            case "圆柱面": return 2;
            case "球面": return 3;
            case "圆锥面": return 3;
            case "环面": return 4;
            case "B样条曲面": return 5;
            case "贝塞尔曲面": return 5;
            case "回转面": return 3;
            case "扫掠面": return 4;
            case "偏移面": return 4;
            default: return 2;
        }
    }

    private void parseBasicInfo(String content, STEPAnalysisResult result) {
        result.setAnalysisTime(java.time.LocalDateTime.now());

        // 解析STEP文件头部信息
        Pattern headerPattern = Pattern.compile("FILE_DESCRIPTION\\s*\\(\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = headerPattern.matcher(content);
        if (matcher.find()) {
            result.setDescription(matcher.group(1).replaceAll("'", "").trim());
        }

        // 解析创建信息
        Pattern timePattern = Pattern.compile("FILE_NAME\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        matcher = timePattern.matcher(content);
        if (matcher.find()) {
            result.setCreationInfo(matcher.group(1).trim());
        }

        // 解析CAD软件信息
        Pattern softwarePattern = Pattern.compile("originating_system\\s*'([^']+)'", Pattern.CASE_INSENSITIVE);
        matcher = softwarePattern.matcher(content);
        if (matcher.find()) {
            result.setCadSoftware(matcher.group(1).trim());
        }

        // 解析STEP版本
        Pattern versionPattern = Pattern.compile("FILE_SCHEMA\\s*\\(\\s*\\(\\s*'([^']+)'", Pattern.CASE_INSENSITIVE);
        matcher = versionPattern.matcher(content);
        if (matcher.find()) {
            result.setStepVersion(matcher.group(1).trim());
        }

        // 解析单位信息
        Pattern unitPattern = Pattern.compile("#\\d+\\s*=\\s*\\(\\s*LENGTH_UNIT\\s*\\(\\s*\\)\\s*NAMED_UNIT\\s*\\(\\s*\\*\\s*\\)\\s*SI_UNIT\\s*\\(\\s*\\.([A-Z]+)\\.", Pattern.CASE_INSENSITIVE);
        matcher = unitPattern.matcher(content);
        if (matcher.find()) {
            result.setUnit(matcher.group(1).toUpperCase());
        } else {
            result.setUnit("MM"); // 默认单位毫米
        }

        // 统计几何实体
        Map<String, Integer> entityCounts = new HashMap<>();
        String[] entityTypes = {
            "CARTESIAN_POINT", "DIRECTION", "VECTOR",
            "LINE", "CIRCLE", "ELLIPSE", "B_SPLINE_CURVE",
            "PLANE", "CYLINDRICAL_SURFACE", "SPHERICAL_SURFACE", "B_SPLINE_SURFACE",
            "ADVANCED_FACE", "CLOSED_SHELL", "MANIFOLD_SOLID_BREP"
        };

        for (String entityType : entityTypes) {
            Pattern pattern = Pattern.compile("#\\d+\\s*=\\s*" + entityType, Pattern.CASE_INSENSITIVE);
            int count = countMatches(pattern, content);
            if (count > 0) {
                entityCounts.put(entityType, count);
            }
        }
        result.setGeometricEntities(entityCounts);

        // 估算模型复杂度
        int totalEntities = entityCounts.values().stream().mapToInt(Integer::intValue).sum();
        String complexity;
        if (totalEntities < 100) {
            complexity = "简单";
        } else if (totalEntities < 1000) {
            complexity = "中等";
        } else {
            complexity = "复杂";
        }
        result.setComplexity(complexity);

        // 解析材料信息
        List<String> materials = parseMaterialInfo(content);
        result.setMaterials(materials);

        // 设置材料类型（取第一个材料作为主要材料类型）
        if (!materials.isEmpty() && !materials.get(0).equals("未指定材料")) {
            result.setMaterialType(materials.get(0));
        }

        log.debug("基础信息解析完成 - 实体总数: {}, 复杂度: {}, 单位: {}",
            totalEntities, complexity, result.getUnit());
    }

    /**
     * 解析材料信息
     */
    private List<String> parseMaterialInfo(String content) {
        List<String> materials = new ArrayList<>();

        // 查找材料指定信息
        Pattern materialPattern = Pattern.compile("MATERIAL_DESIGNATION\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = materialPattern.matcher(content);
        while (matcher.find()) {
            String material = matcher.group(1).replaceAll("'", "").trim();
            if (!material.isEmpty()) {
                materials.add(material);
            }
        }

        // 查找材料属性
        Pattern materialPropertyPattern = Pattern.compile("MATERIAL_PROPERTY\\s*\\(([^)]+)\\)", Pattern.CASE_INSENSITIVE);
        matcher = materialPropertyPattern.matcher(content);
        while (matcher.find()) {
            String property = matcher.group(1).replaceAll("'", "").trim();
            if (!property.isEmpty() && !materials.contains(property)) {
                materials.add(property);
            }
        }

        // 如果没有找到材料信息，设置默认值
        if (materials.isEmpty()) {
            materials.add("未指定材料");
        }

        return materials;
    }
}
